﻿using System;

namespace Modbus
{
	/// <summary>
	/// 
	/// </summary>
	public partial class ModbusClient : IDisposable
	{
		private IModbusClientTransport transport;
		private readonly bool isOwner;
		private bool isDisposed;

		#region ( Constructors )

		/// <summary>
		/// 
		/// </summary>
		/// <param name="transport"></param>
		/// <exception cref="ArgumentNullException"></exception>
		public ModbusClient(IModbusClientTransport transport)
			: this(transport, true)
		{
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="transport"></param>
		/// <param name="isOwner"></param>
		/// <exception cref="ArgumentNullException"></exception>
		public ModbusClient(IModbusClientTransport transport, bool isOwner)
		{
			if (transport == null)
			{
				throw new ArgumentNullException("transport");
			}

			this.transport = transport;
			this.isOwner = isOwner;
		}

		#endregion

		#region ( IDisposable )

		/// <summary>
		/// 
		/// </summary>
		public void Dispose()
		{
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="disposing"></param>
		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (this.isOwner && (this.transport != null))
				{
					this.transport.Dispose();
				}
			}

			this.transport = null;
			this.isDisposed = true;
		}

		#endregion

		/// <summary>
		/// 
		/// </summary>
		/// <exception cref="ObjectDisposedException"></exception>
		protected void ThrowIfDisposed()
		{
			if (this.isDisposed)
			{
				// TODO: Insert exception message.
				throw new ObjectDisposedException(null, "");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <value></value>
		public bool IsDisposed
		{
			get { return isDisposed; }
		}

		/// <summary>
		/// 
		/// </summary>
		/// <value></value>
		public bool IsTransportOwner
		{
			get { return this.isOwner; }
		}

		/// <summary>
		/// 
		/// </summary>
		/// <value></value>
		public IModbusClientTransport Transport
		{
			get
			{
				this.ThrowIfDisposed();
				return this.transport;
			}
		}
	}
}
